// pages/master/mainten/famMainten/childMedHistory/addHistory/addHistory.js
const app = getApp();
var util = require("../../../../../../utils/util.js")
const db = wx.cloud.database()
const _ = db.command
const historyDB=db.collection('childMedicalHistory')
var fnum=null
var cname=null
var publishPicture =[] 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addpic_hidden:false,
    temPicture:[],
    constitutionArray: ['平和质', '气虚质', '阳虚质', '阴虚质','痰湿质','湿热质','血瘀质','气郁质','特禀质'],
    index:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    fnum=options.famnum
    cname = options.childName
  },

  bindPickerChange: function(e) {
    this.setData({
      index: e.detail.value
    })
  },
  //添加图片
  addPicture:function(){
    let that = this
    wx.chooseImage({
            count: 3-that.data.temPicture.length, //最多选择三张图片
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                console.log(res)
                var tempFiles = res.tempFiles
                  tempFiles.forEach((eachFile,index)=>{
                      that.data.temPicture =  that.data.temPicture.concat(eachFile.path)
                      if(that.data.temPicture.length>=3){
                        that.setData({
                          addpic_hidden:true
                        })
                      }
                      that.setData({
                        temPicture: that.data.temPicture
                      })
                  }
              )
            }
          })
  },

  previewImage: function (e) {
    app.previewImage(e)
  },

  //删除图片  （点击红叉叉）
  deletePicture:function(e){
    let that = this
    let picid = e.currentTarget.id
    console.log(e.currentTarget.id)
      wx.showModal({
        title: '',
        content: '要删除这张照片吗？',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.data.temPicture.splice(that.data.temPicture.findIndex(e => e === picid), 1) 
            that.setData({
              temPicture: that.data.temPicture,
              addpic_hidden:false
            })
            console.log(that.data.temPicture)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
  },

  //上传图片到云存储
  uploadPicture:function(fileUrl,cloudUrl){
    let that = this
    that.data.temPicture.forEach((item,i)=>{      
      wx.cloud.uploadFile({
          cloudPath: String(cloudUrl)+i+'.jpg', // 上传至云端的路径
          filePath: fileUrl[i], // 小程序临时文件路径
          success: res => {
            console.log(res.fileID)
            publishPicture.push(res.fileID)
            upsuccess = true
          },
          fail: res => {
            upsuccess = false
          }
        })
    })
  },
  clickSure:function(e){
    console.log(e)
      wx.showLoading()
      let that = this
      let _constitution = e.detail.value.constitution
      let _other=  e.detail.value.other
      let _pathogeny = e.detail.value.pathogeny
           let imgid = fnum+new Date().getTime()
           // console.log(publishid)
            let promiseMethod = new Array(that.data.temPicture.length)
            that.data.temPicture.forEach((item,i)=>{
                    promiseMethod[i] = wx.cloud.uploadFile({
                        cloudPath: String(imgid)+i+'.jpg',
                        filePath: that.data.temPicture[i]
                    }).then(res => {
                      publishPicture.push(res.fileID)
                    })
                })
        
            Promise.all([...promiseMethod]).then(() => {
              historyDB.add({  //公告数据库添加一则公告
                data:{
                  ChildName:cname,
                  FamilyNum:fnum,
                  date:util.formatDateTime(new Date()),
                  constitution:_constitution,
                  pathogeny:_pathogeny,
                  other:_other,
                  photos:publishPicture
                },success:function(res){
                  wx.hideLoading({
                    success: (res) => {
                      wx.showToast({
                        title: '添加成功',
                        icon:'success'
                      })
                      var pages = getCurrentPages() 
                      var currentPage = pages[pages.length-2] 
                      let opt = {}
                      opt.famnum=fnum
                      opt.childName=cname
                      currentPage.onLoad(opt)
                      
                      wx.navigateBack()
                    },
                  })
                  },fail:function(res){
                    console.log("系统出错")
                    wx.showToast({
                      title: '系统出错',
                      icon:"none"
                    })
                  }
              })
            })
       
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})